package com.cll.prototype.email.service.impl;

import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.email.dto.TemplateEmailDto;
import com.cll.prototype.email.service.IEmailService;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;

/**
 * 描述信息:
 * 短信发送服务
 * @author CLL
 * @version 1.0
 * @date 2020/10/27 17:41
 */
@Service
public class EmailServiceImpl implements IEmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    private static final String START_HTML = "<html>";
    private static final String END_HTML = "</html>";

    @Value("${spring.mail.username}")
    private String defaultSendEmailFrom;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Override
    public AjaxResult sendEmail(String from, String to, String subject, String content){
        if (StringUtils.isAnyBlank(to, subject, content)) {
            return AjaxResult.error(41, "参数不合法");
        }
        if (StringUtils.isBlank(from)) {
            from = defaultSendEmailFrom;
        }
        if (content.contains(START_HTML) && content.contains(END_HTML)) {
            return sendHtmlEmail(from, to, subject, content);
        } else {
            return sendTextEmail(from, to, subject, content);
        }
    }

    @Override
    public AjaxResult sendTextEmail(String from, String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        javaMailSender.send(message);
        return AjaxResult.success(20, "发送邮件成功");
    }

    @Override
    public AjaxResult sendHtmlEmail(String from, String to, String subject, String content) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setText(content, true);

            javaMailSender.send(mimeMessage);
        } catch (MessagingException me) {
            logger.error("****** 邮件发送异常" + me.getMessage(), me);
            return AjaxResult.error(50, "邮件发送异常");
        }
        return AjaxResult.success(20, "发送成功");
    }

    @Override
    public AjaxResult sendAttachmentEmail(String from, String to, String subject, String content, String filePath) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setText(content, true);

            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            String filename = fileSystemResource.getFilename();
            if (StringUtils.isBlank(filename)) {
                filename = "默认附件";
            }
            mimeMessageHelper.addAttachment(filename, fileSystemResource);

            javaMailSender.send(mimeMessage);
        } catch (MessagingException me) {
            logger.error("****** 邮件发送异常" + me.getMessage(), me);
            return AjaxResult.error(50, "邮件发送异常");
        }
        return AjaxResult.success(20, "发送成功");
    }

    @Override
    public AjaxResult sendInlineEmail(String from, String to, String subject, String content, String inlineId, String inlinePath) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setText(content, true);

            FileSystemResource inlineFile = new FileSystemResource(inlinePath);
            mimeMessageHelper.addInline(inlineId, inlineFile);

            javaMailSender.send(mimeMessage);
        } catch (MessagingException me) {
            logger.error("****** 邮件发送异常" + me.getMessage(), me);
            return AjaxResult.error(50, "邮件发送异常");
        }
        return AjaxResult.success(20, "发送成功");
    }

    @Override
    public AjaxResult sendTemplateEmail(String from, String to, String subject, String templateName, Map<String, String> templateParams) {
        Context context = new Context();
        for (Map.Entry<String, String> entry: templateParams.entrySet()) {
            context.setVariable(entry.getKey(), entry.getValue());
        }
        String emailContent = templateEngine.process(templateName, context);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setText(emailContent, true);

            javaMailSender.send(mimeMessage);
        } catch (MessagingException me) {
            logger.error("****** 邮件发送异常" + me.getMessage(), me);
            return AjaxResult.error(50, "邮件发送异常");
        }
        return AjaxResult.success(20, "发送成功");
    }

    @Override
    public AjaxResult sendTemplateEmail(String from, String to, String subject, TemplateEmailDto templateEmailDto) {
        if (StringUtils.isBlank(from)) {
            from = defaultSendEmailFrom;
        }
        Context context = new Context();
        @NonNull String templateName = templateEmailDto.getTemplateName();
        @NonNull Map<String, String> templateParams = templateEmailDto.getParams();
        for (Map.Entry<String, String> entry: templateParams.entrySet()) {
            context.setVariable(entry.getKey(), entry.getValue());
        }
        String emailContent = templateEngine.process(templateName, context);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setSentDate(new Date());
            mimeMessageHelper.setText(emailContent, true);

            javaMailSender.send(mimeMessage);
        } catch (MessagingException me) {
            logger.error("****** 邮件发送异常" + me.getMessage(), me);
            return AjaxResult.error(50, "邮件发送异常");
        }
        return AjaxResult.success(20, "发送成功");
    }
}
